package com.rain.lo.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.rain.lo.common.utils.ResultUtil;
import com.rain.lo.entity.Project;
import com.rain.lo.service.ProjectService;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class ProjectController {

    @Resource
    private ProjectService projectService;

    @RequestMapping("project.html")
    public String toProject(Model model) {
        model.addAttribute("pMap",projectService.list());
        return "project/list";
    }

    @ResponseBody
    @RequestMapping("list/project")
    public Object list() {
        //获取一级目录
        List<Project> list = projectService.list(0);
        List<Project> listAll = projectService.list();
        Map<Integer,Pro> map = list.stream().collect(Collectors.toMap(Project::getId,p->new Pro(p,Lists.newArrayList())));
        listAll.forEach(p->{
            if (p.getParent()!=0){
                Pro pro = map.get(p.getParent());
                pro.getChildren().add(new Pro(p,null));
            }
        });
        return map.values();
    }

    @Data
    static class Pro{
        int id;
        String text;
        List<Pro> children;
        Pro(Project p,List<Pro> children){
            this.id=p.getId();
            this.text=p.getName();
            this.children=children;
        }
    }
}
